package com.sanjiahantang.ythshopping.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.sanjiahantang.ythshopping.R;
import com.sanjiahantang.ythshopping.activity.MainActivity;
import com.sanjiahantang.ythshopping.activity.SearchActivity;
import com.sanjiahantang.ythshopping.activity.me.JsWebActivity;
import com.sanjiahantang.ythshopping.activity.me.NewAreaListActivity;
import com.sanjiahantang.ythshopping.activity.me.SelectAreaActivity;
import com.sanjiahantang.ythshopping.adapter.home.HomeAdapter;
import com.sanjiahantang.ythshopping.config.ConfigValue;
import com.sanjiahantang.ythshopping.model.Area;
import com.sanjiahantang.ythshopping.model.AreaBean;
import com.sanjiahantang.ythshopping.model.BestNewHot;
import com.sanjiahantang.ythshopping.model.HomePageData;
import com.sanjiahantang.ythshopping.model.HomePageModel;
import com.sanjiahantang.ythshopping.model.HomePageMoreModel;
import com.sanjiahantang.ythshopping.presenter.HomePagePresenter;
import com.sanjiahantang.ythshopping.qrzxing.CaptureActivity;
import com.sanjiahantang.ythshopping.utils.SPUtils;
import com.sanjiahantang.ythshopping.utils.Utils;
import com.sanjiahantang.ythshopping.views.HomePageMoreView;
import com.sanjiahantang.ythshopping.views.HomePageView;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2017/6/7.
 */

public class HomeFragment extends BaseFragment implements HomePageView, HomePageMoreView ,AMapLocationListener {

    private View rootView;
    private RecyclerView mRecyclerView;
    private TextView scan;
    private TextView category;
    private SwipeRefreshLayout refreshLayout;
    protected  View titelv;

    private List<Integer> typeList = new ArrayList<>();

    private HomePageData homePageData;
    private LinearLayout search;


    HomePagePresenter presenter;

    private LinearLayoutManager layoutManager;

    private boolean isFreshing;

    private List<BestNewHot> moreList;

    private HomeAdapter adapter;

    private RecyclerView.OnScrollListener scrollListener;
    //定位
    public AMapLocationClientOption mLocationOption;
    private AMapLocationClient mlocationClient;

    private boolean hasData = false;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        for (int i = 1; i < 8; i++) {
            typeList.add(i);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView != null) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.fragment_home, container, false);
        }

        return rootView;
    }

    @Override
    protected void initView() {

        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        scan = (TextView) rootView.findViewById(R.id.txtScanning);
        category = (TextView) rootView.findViewById(R.id.txtMessage);
        search = (LinearLayout) rootView.findViewById(R.id.lineLaySearch);
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.home_page_refresh);
        titelv=rootView.findViewById(R.id.home_top);



        scan.setOnClickListener(this);
        category.setOnClickListener(this);
        search.setOnClickListener(this);
        layoutManager = new LinearLayoutManager(context);
        mRecyclerView.setLayoutManager(layoutManager);

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (isFreshing) {
                    return;
                } else {
                    refreshLayout.setRefreshing(true);
                    isFreshing = true;

                    initData();
                }
            }
        });
        scrollListener = new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if(hasData){
                    LinearLayoutManager linearLayoutManager= (LinearLayoutManager) recyclerView.getLayoutManager();
                    if (linearLayoutManager.findFirstVisibleItemPosition()>=1)
                    {
                        titelv.setBackgroundColor(context.getResources().getColor(R.color.prospect));
                    }else {
                        titelv.setBackgroundColor(context.getResources().getColor(R.color.prospect));
                    }
                }

            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }
        };
        mLocationOption = null;
        mlocationClient = new AMapLocationClient(context);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setInterval(1000*60*30);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();
        presenter = new HomePagePresenter(this);

    }

    @Override
    protected void initData() {
        if(ConfigValue.currentCity != null){
            presenter.getHomePageData(context);
        }

    }


    @Override
    protected void initTitle() {

    }

    @Override
    public void getData(HomePageModel response) {
        if(response!=null)
        {
            if (response.getCode().equals("200")) {
                hasData = true;
                refreshLayout.setRefreshing(false);
                isFreshing = false;
                homePageData = response.getData();
//                ConfigValue.rid = homePageData.getArea();
                if(homePageData.getArea() == null){
                    ConfigValue.rid = ConfigValue.currentCity.getRegion_id();
                }else{
                    ConfigValue.rid = homePageData.getArea();
                }
                adapter = new HomeAdapter(context, typeList, homePageData, (MainActivity) getActivity());
                mRecyclerView.setLayoutManager(layoutManager);
                mRecyclerView.setAdapter(adapter);
            } else {
                Log.d("HOMEFRAGMENT", "response: ");
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if(ConfigValue.currentCity != null ){
            category.setText(ConfigValue.currentCity.getRegion_name());
        }

        mRecyclerView.addOnScrollListener(scrollListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e("onPause", "onPause: ");
        mRecyclerView.removeOnScrollListener(scrollListener);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.txtScanning:
                if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(getContext())) {
                    return;
                }
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);

                } else {
                    Intent itCapture = new Intent(getActivity(), CaptureActivity.class);
                    itCapture.putExtra("type","home");
                    startActivity(itCapture);

                }


                break;

            case R.id.txtMessage:
//                Intent it = new Intent(context,SelectAreaActivity.class);
                Intent it = new Intent(context,NewAreaListActivity.class);
                it.putExtra("from","main");
                startActivityForResult(it, 1);
                break;

            case R.id.lineLaySearch:
                Intent search = new Intent(context, SearchActivity.class);
                startActivity(search);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent itCapture = new Intent(getActivity(), CaptureActivity.class);
                startActivity(itCapture);

            } else {
                Toast.makeText(context, "权限被禁止，相关功能无法使用！", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    public void getMoreData(HomePageMoreModel response) {
        refreshLayout.setRefreshing(false);
        if (response.getCode().equals("200")) {
            moreList = response.getData();
            homePageData.getBest().addAll(moreList);
            adapter.notifyDataSetChanged();
        } else if (response.getCode().equals("500")) {
            Toast.makeText(getActivity(), "已经到底了！", Toast.LENGTH_SHORT).show();
        } else {
            String msg = response.getMsg().toString();
            if (TextUtils.isEmpty(msg)) {

            } else
                Toast.makeText(getActivity(), response.getMsg().toString(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {


        if(ConfigValue.MANUALLY || ConfigValue.LOCATED ){
            return;
        }

        if (Build.VERSION.SDK_INT >= 23) {
            int checkPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                Log.d("TTTT", "弹出提示");
            }
        }
//        String province = "北京";
        String city = "北京";
        if (aMapLocation!=null)
        {
            if(aMapLocation.getErrorCode()==0)
            {

                ConfigValue.Latitude = aMapLocation.getLatitude();
                ConfigValue.Longitude = aMapLocation.getLongitude();
//                province = aMapLocation.getProvince();
                if(SPUtils.get(context,"lastCity","").equals("")){
                    city = aMapLocation.getCity();
                    AreaBean.City model = new AreaBean.City();

                    if(city != null && city.contains("市")){
                        city = city.replace("市","");
                    }
                    model.setRegion_name(city);
                    model.setParent_name(aMapLocation.getProvince());
                    ConfigValue.currentCity = model;
                    SPUtils.put(context,"lastCity",new Gson().toJson(model));
                    AreaBean.addHistory(context,model);
                }else{
                    city = loadSPCity();
                }


                ConfigValue.LOCATED = true;


            }else{
                city = loadSPCity();
            }




        }else{
            city = loadSPCity();
        }
//        if (ConfigValue.arealist.size()!=0)
//        {
//            ConfigValue.arealist.clear();
//        }
//
//        Area areaP = new Area();
//        areaP.setRegion_name(province);
//        ConfigValue.arealist.add(areaP);
//
//        Area areaC = new Area();
//        areaC.setRegion_name(city);
//        ConfigValue.arealist.add(areaC);

        category.setText(city);
        presenter.getHomePageData(context);

    }

    private String loadSPCity(){
        AreaBean.City bean = new Gson().fromJson(SPUtils.get(context,"lastCity","{}").toString(), AreaBean.City.class);
        String city = bean.getRegion_name();
        ConfigValue.currentCity = bean;
        if(bean.getRegion_id() != null && !TextUtils.isEmpty(bean.getRegion_id())){
            ConfigValue.rid = bean.getRegion_id();
        }

        return city;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1)
        {
            if (resultCode==2)
            {
                ConfigValue.currentCity = new Gson().fromJson(data.getStringExtra("city"), AreaBean.City.class);
                ConfigValue.MANUALLY = true;
                category.setText(ConfigValue.currentCity.getRegion_name());
                SPUtils.put(context,"lastCity",new Gson().toJson(ConfigValue.currentCity));
                ConfigValue.rid = ConfigValue.currentCity.getRegion_id();
                presenter.getHomePageData(context);
            }
        }
    }
}
